import React, { useEffect, useRef } from "react";
import BScroll from "@better-scroll/core";
import { throttle } from "lodash";

export let bs = null; //bs对象
let cbs = [];
const style = {
	height: "100%",
	overflow: "hidden"
};
const onScroll = bs => {
	if (bs) {
		if (cbs.length > 0) {
			bs.on(
				"scroll",
				throttle(() => {
					cbs.forEach(cb => cb());
				}, 1000)
			);
		}
	}
};
const initScroll = dom => {
	if (dom) {
		bs = new BScroll(dom, {
			scrollX: true,
			click: true,
			scrollY: true,
			probeType: 3
		});
		onScroll(bs);
	}
};

const Scroll = props => {
	const { children, isScroll, ..._props } = props;
	const ref = useRef(null);
	useEffect(() => {
		if (isScroll) {
			initScroll(ref.current);
		}
		// return () => {
		// 	if (bs && isScroll) {
		// 		bs.destroy();
		// 	}
		// };
	}, [ref]);
	if (isScroll) {
		return (
			<div ref={ref} style={style} {..._props}>
				{children}
			</div>
		);
	}
	return children;
};
export const removeListener = () => {
	if (bs) {
		bs.destroy();
		cbs.length = 0;
	}
};
//刷新
export const refresh = () => {
	if (bs) {
		setTimeout(() => bs.refresh(), 0);
	}
};
//监听滚动
export const listener = cb => {
	if (typeof cb === "function") {
		cbs.push(cb);
	} else {
		throw new Error("callback is not function");
	}
};

// window.addEventListener("hashchange", refresh);
export default Scroll;
